using Avalonia.BiliBili.Views.ChildViews.Search;
using Avalonia.Extensions.Controls;
using Avalonia.Extensions.Event;
using Bilibili.Common;
using Bilibili.Model.Common;
using Bilibili.Model.Search;
using DynamicData;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Avalonia.BiliBili.Views.ChildViews
{
    public partial class SearchLive : ChildView
    {
        private int PageNum { get; set; } = 1;
        private ObservableCollection<SearchLiveRoomItem> Items { get; }
        public SearchLive()
        {
            InitializeComponent();
            Items = [];
        }
        public override void Callback(object data)
        {
            RunOnUiThread(async () =>
            {
                if (data is InvokeData<string> info)
                {
                    if (info.Clear)
                        Items.Clear();
                    var result = await Base.Client.GetLives(info.Data, PageNum);
                    if (result.IsSuccess())
                    {
                        var models = result.Data["result"]["live_room"].ToObject<List<SearchLiveRoomItem>>();
                        Items.AddRange(models);
                    }
                    else
                        PopupToast.Show(result?.Message);
                }
            });
        }
        public override void AfterInitializeComponent()
        {
            livingList.ItemsSource = Items;
            livingList.ItemClick += LivingList_ItemClick;
        }
        private void LivingList_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.IsLeftClick && e.ClickItem is ListViewItem item && item.Content is SearchLiveRoomItem roomItem)
                    App.Mapper.NavigateToPlayer(roomItem.roomid, PlayMode.Live);
            }
            catch { }
        }
    }
}